﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;

class UpdateProgram
{
	static FileSystemWatcher watcher;
	static string last;
	static int i = 0;

	public static void Main()
	{
		//Listen file system
		watcher = new FileSystemWatcher(Application.StartupPath);
		watcher.Changed += new FileSystemEventHandler(watcher_Changed);
		watcher.Created += new FileSystemEventHandler(watcher_Changed);
		watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite |
			NotifyFilters.FileName | NotifyFilters.DirectoryName;
		watcher.WaitForChanged(WatcherChangeTypes.All, 1000);
		watcher.EnableRaisingEvents = true;

		//Sleep thread
		System.Threading.Thread.Sleep(Timeout.Infinite);
	}

	static void watcher_Changed(object sender, FileSystemEventArgs e)
	{
		//If something changed
		if (e.Name == last)
			i++;
		else
			i = 0;
		last = e.Name;
		if (i == 2)
		{
			i = 0;
			FileInfo f = new FileInfo(e.FullPath);

			try
			{
				//classify by extension
				if (e.Name == "restart.cmd")	//If .cmd, then restart process
				{
					if (Process.GetProcessesByName("Car").Length > 0)
					{
						Process.GetProcessesByName("Car")[0].Kill();
					}
					Process.Start("Car.exe");
					Console.WriteLine("{0} -> {1}", DateTime.Now, e.Name);
				}
				else if (f.Extension == ".hex") //If .hex file, then program the micro-controller
				{
					Process.Start(
						"avrdude",
						"-p m2560 -b 115200 -c stk500v2 -C avrdude.conf -P COM2 -U flash:w:"+e.Name+":a");
					Console.WriteLine("{0} -> {1}", DateTime.Now, e.Name);
				}
			}
			catch
			{
				Console.WriteLine("{0} -> {1} failed", DateTime.Now, e.Name);
			}
		}
	}
}